package ch.gibb.javamvc;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.log4j.Logger;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Loads the vm-Files from the war-file
 *
 * @author Bernard Jaquet
 * @version 1.0
 */
public class ResourceLoaderImp extends ResourceLoader {

    /**
     * Instance of logger
     */
    private final Logger masterLogger = Logger.getLogger(ResourceLoaderImp.class);

    /**
     * Instance of the actual request to the Server
     */
    private WebPageMapper wp;

    public ResourceLoaderImp(WebPageMapper wp) {
        this.wp = wp;
    }

    @Override
    public void init(ExtendedProperties configuration) {

    }

    /**
     * Generates an InputStream from the given file name
     *
     * @param source
     * @return
     * @throws ResourceNotFoundException
     */
    @Override
    public InputStream getResourceStream(String source) throws ResourceNotFoundException {
        try {
            if (source.equals("VM_global_library.vm"))
                return null;
            masterLogger.debug("Triing to get view with name " + source);
            URL url = wp.getServerURL(source);
            masterLogger.debug("Res is " + url);
            if (url == null)
                throw new ResourceNotFoundException("Resource could not be found");
            return url.openStream();
        } catch (ResourceNotFoundException e) {
            throw e;
        } catch (Exception e) {
            String msg = "Could not open stream because " + e.getMessage();
            masterLogger.error(msg, e);
            throw new ResourceNotFoundException(msg, e);
        }
    }

    @Override
    public boolean isSourceModified(Resource resource) {
        long lastModification = getLastModified(resource);
        return (lastModification == 0 || lastModification != resource.getLastModified());
    }

    @Override
    public long getLastModified(Resource resource) {
        try {
            if (resource.getName().equals("VM_global_library.vm"))
                return -1;
            URL url = wp.getServerURL(resource.getName());
            URLConnection connection = url.openConnection();
            return connection.getLastModified();
        } catch (Exception e) {
            masterLogger.error("Could not load Resource because " + e.getMessage(), e);
            return -1;
        }
    }
}
